#include <QtGui>
#include "dragtreewidget.h"
#include "attribute.h"
#include "attributesmodel.h"
//
DragTreeWidget::DragTreeWidget( QWidget *p) 
	: QTreeWidget(p)
{
    setAcceptDrops(true);
    setDragEnabled(true);
    setDragDropMode(QAbstractItemView::DragDrop);
    setRootIsDecorated(false);
	headerItem()->setHidden(true);
	_attributes = 0;
	_menu_dominant = false;
	setAcceptCrdOnTopLevel();
}
//
void DragTreeWidget::dragEnterEvent(QDragEnterEvent *event)
{
//	qDebug("dragEnterEvent");
    if (event->mimeData()->hasFormat("application/x-attribute")) {
        if (children().contains(event->source())) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            event->acceptProposedAction();
        }
    } else if (event->mimeData()->hasText()) {
        event->acceptProposedAction();
    } else {
       QTreeWidget::dragEnterEvent(event);// event->ignore();
    }
}

void DragTreeWidget::dragMoveEvent(QDragMoveEvent *event)
{
//	qDebug("dragMoveEvent");
    if (event->mimeData()->hasFormat("application/x-attribute")) {
        if (children().contains(event->source())) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            event->acceptProposedAction();
        }
    } else if (event->mimeData()->hasText()) {
        event->acceptProposedAction();
    } else {
	  QTreeWidgetItem *pItem = itemAt(event->pos());
	  if(pItem)		  
		  event->accept();	
	  else
	      event->ignore();
    }
}

void DragTreeWidget::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasFormat("application/x-attribute")) {
        QString text;
        const QMimeData *mime = event->mimeData();
        QByteArray itemData = mime->data("application/x-attribute");
        QDataStream dataStream(&itemData, QIODevice::ReadOnly);
        int    nom;
        Attribute *attr = 0;
        dataStream >> nom;
        attr = _attributes->attribute(nom);
        if(!attr) return;
        	
        text = attr->alias();
// ...
		QTreeWidgetItem *pItem = itemAt(event->pos());
		QTreeWidgetItem *item  = 0;
		if(!pItem){
			item = new QTreeWidgetItem(this,QStringList() << text );				
			item->setForeground(0,QBrush(QColor(0,0,0)));
			item->setFlags(item->flags() | Qt::ItemIsDragEnabled);
		}
		else{
			item = new QTreeWidgetItem(pItem,QStringList() << text );
			expandItem(pItem);
			//printf("hello item");
		}
	// 
		if(item->parent()){
			int pnom = item->parent()->data(0,Qt::UserRole).toInt();
			Attribute *dl = _attributes->attribute(pnom);
			if(dl)
				dl->setPlus(true);
		}

		item->setData(0,Qt::UserRole,nom); // порядковый номер (для связи)
		event->accept();
    } else if (event->mimeData()->hasText()) {
        QStringList pieces = event->mimeData()->text().split(QRegExp("\\s+"),QString::SkipEmptyParts);
        QPoint position = event->pos();
        event->acceptProposedAction();
    } else {
		QTreeWidget  *source = (QTreeWidget *)event->source();
		QTreeWidgetItem *pItem = itemAt(event->pos());
		QTreeWidgetItem *item  = 0, *olditem=0;
		if(source && pItem){
			olditem = source->currentItem();
			if(olditem && olditem!=pItem){
				//qDebug() << "adding items with clone";
				item = olditem->clone();
				item = item->clone();
				pItem->addChild(item);
				pItem->setExpanded(true);
				item->setExpanded(true);
				if(pItem->parent()==NULL && pItem->child(0)==item){
					setDominant(item);					
				}

				emit itemChanged(item,0);
				event->accept();
			}
			else
				event->ignore();
		}
		else
			event->ignore();
   }
}
//

// 
void DragTreeWidget::contextMenuEvent ( QContextMenuEvent * e )  
{
	if(itemAt(e->pos())){
		QMenu menu;
		//connect(menu.addAction(trUtf8("Редактировать...")),SIGNAL(triggered()),this,SLOT(slotEditItem()));
		if(_menu_dominant) connect(menu.addAction(trUtf8("Доминантная")),SIGNAL(triggered()),this,SLOT(slotDominant()));
		connect(menu.addAction(trUtf8("Удалить")),SIGNAL(triggered()),this,SLOT(slotRemoveDomen()));
		menu.exec(e->globalPos());
	}
}
//
void DragTreeWidget::slotEditItem()
{
	emit editItem(currentItem());
}
//
void DragTreeWidget::slotRemoveDomen()
{
	QTreeWidgetItem *item = currentItem();
	if(item){
		if(item->parent()){
			if(item->parent()->childCount()==1){
				int pnom = item->parent()->data(0,Qt::UserRole).toInt();
				Attribute *dl = _attributes->attribute(pnom);
				if(dl)
					dl->setPlus(false);
			}
			item->parent()->takeChild(item->parent()->indexOfChild(item));
//			emit itemChanged(item,0);
		} 
		else{

			delete item;
			item = 0;
		}
	}
	emit itemChanged(item,0);	
}
//
void DragTreeWidget::slotDominant()
{
	QTreeWidgetItem *item = currentItem();
	if(item)
		setDominant(item);
}
//
void DragTreeWidget::showMenuDominant(bool show)
{
	_menu_dominant = show;
}
//
void DragTreeWidget::showDominant(bool show)
{
	_show_dominant = show;
}
//
// пометить item как доменантный атрибут, выделив красным цветом
void DragTreeWidget::setDominant(QTreeWidgetItem *item)
{
	item->setForeground(0,QBrush(Qt::red));				
}

void DragTreeWidget::setAttributes(AttributesModel *attr)
{
	_attributes = attr;
}

void DragTreeWidget::setAcceptCrdOnTopLevel(bool ac)
{
	_accept_crd_on_toplevel = ac;
}

void DragTreeWidget::keyPressEvent(QKeyEvent *e)
{
	
	if(e->key()==Qt::Key_Delete){
		//qDebug() << Q_FUNC_INFO << e->key();
		foreach(QModelIndex index,selectedIndexes()){
			qDebug() << "removing";
			model()->removeRow(index.row(),index.parent());
		}
	}
}
